﻿using System;

using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using System.Drawing;
using Silvermoon.Visuals;
using System.Diagnostics;

namespace Silvermoon.Core
{
    /// <summary>
    /// Provides layout functionality.
    /// </summary>
    internal static class LayoutEngine
    {

        /// <summary>
        /// Sets the boundaries of a control depending on the container's size and it's margins.
        /// </summary>
        /// <param name="control">The control for which to set the Bounds.</param>
        /// <param name="parent">The size of the parent container.</param>
        public static void Layout(Control control, Size containerSize)
        {
            Margin m = control.Margin;
            Rectangle b = control.Bounds;

            if (m.Left != null && m.Right != null)
            {
                b.X = m.LeftZero;
                b.Width = containerSize.Width - m.Width;
            }
            else
            {
                if (m.Left != null) b.X = m.LeftZero;
                if (m.Right != null) b.X = containerSize.Width - b.Width - m.RightZero;
            }

            if (m.Top != null && m.Bottom != null)
            {
                b.Y = m.TopZero;
                b.Height = containerSize.Height - m.Height;
            }
            else
            {
                if (m.Top != null) b.Y = m.TopZero;
                if (m.Bottom != null) b.Y = containerSize.Height - b.Height - m.BottomZero;
            }

            control.Bounds = b;
        }

        /// <summary>
        /// Sets the boundaries of all children of a control that implements ICompositeControl relative to the size of this control and their margins.
        /// </summary>
        /// <param name="control">A control which must implement ICompositieControl.</param>
        public static void LayoutChildren(Control control)
        {
            IList<Control> children = ((ICompositeControl)control).Controls;
            if (children != null)
            {
                Size size = control.Size;
                foreach (Control c in children)
                {
                    if (!c.Margin.IsEmpty) Layout(c, size);
                }
            }
        }
    }
}
